using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace SpoonStream
{
	public class UDPSimulator
	{
		private byte[] _buffer = new byte[65000];
		private NetworkQueue<byte[]> _queue = new NetworkQueue<byte[]>();
		private Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		private SocketFlags _flags;
		private EndPoint _endPoint = new IPEndPoint(IPAddress.Any, 0);
		private IPPacketInformation _packetInfo;

		private IPEndPoint _destination = new IPEndPoint(IPAddress.Loopback, 1234);

		public UDPSimulator()
		{
			_queue.OnReceive += new NetworkQueue<byte[]>.OnReceiveHandler(_queue_OnReceive);
			_socket.Bind(new IPEndPoint(IPAddress.Any, 1000));
			_socket.BeginReceiveMessageFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref _endPoint,
											new AsyncCallback(Receive), null);
		}

		private void Receive(IAsyncResult ar)
		{
			int count = _socket.EndReceiveMessageFrom(ar, ref _flags, ref _endPoint, out _packetInfo);

			byte[] tmp = new byte[count];
			Array.Copy(_buffer, tmp, count);
			_queue.Enqueue(tmp);

			_socket.BeginReceiveMessageFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref _endPoint,
														new AsyncCallback(Receive), null);
		}

		private void _queue_OnReceive(byte[] item)
		{
			_socket.SendTo(item, _destination);
		}
	}
}